import { defineStore } from 'pinia';
import { sessionStorageSet, sessionStorageClear } from '@/utils/sessionStorage';
import { localStorageClear } from '@/utils/localStorage';
import { menuTreeApi } from "@/api/menu"
import { roleMenuTreeApi, roleMenuListApi } from "@/api/system"
import { dictApi } from "@/api/dict"
import { listToTree } from '@/utils';

export const useSystemStore = defineStore('system', {
  state: () => ({
    userInfo: null,
    token: null,
    menu: [],
    currentUserMenu: [],
    currentUserMenuList: [],
    currentUserMenuTree: [],
    dict: [],
    dictLoading: false,
  }),
  getters: {
    getShortToken() {
      return this.token;
    },
  },
  actions: {
    async setToken(token) {
      this.token = token;
      sessionStorageSet('token', token)
    },
    async setUserInfo(userInfo) {
      this.userInfo = userInfo;
    },
    async clearAll() {
      sessionStorageClear()
      localStorageClear()
    },
    async loadCurrentUserMenuList(roleId) {
      const currentRoleIds = this.userInfo?.role?.map((item) => item?.id);
      const data = await roleMenuListApi({ roleId: roleId || currentRoleIds });
      this.currentUserMenuList = data || [];
      this.currentUserMenuTree = listToTree({ list: data });
    },
    async reloadMenu(roleId) {
      if (roleId === this.userInfo.role) {
        this.loadCurrentUserMenuList(roleId)
      }
    },
    async loadCurrentUserMenuTree() {
      const data = await roleMenuTreeApi({ roleId: this.userInfo.role });

      roleMenuListApi

      // const data = await roleMenuTreeApi({});
      this.currentUserMenu = data || [];
    },
    async loadMenuTree() {
      const data = await menuTreeApi();
      this.menu = data;
    },
    async loadDictData() {
      this.dictLoading = true;
      const dict = await dictApi();
      this.dict = dict;
      this.dictLoading = false;
    },
    async initDictData() {
      if (!this.dict.length && !this.dictLoading) {
        this.loadDictData()
      }
    }
  },
  // 开启数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        storage: sessionStorage,
      },
    ],
  },
});
